package cool.goodbai.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cool.goodbai.entity.Employ;
import cool.goodbai.entity.Post;
import cool.goodbai.entity.User;
import cool.goodbai.mapper.PostMapper;
import cool.goodbai.mapper.UserMapper;
import cool.goodbai.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Optional;

@Service
public class MailServiceImpl implements MailService {
    @Autowired(required = false)
    private JavaMailSenderImpl javaMailSender;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String sendMail(Employ employ) {
        try {
            // 首先处理邮件模板信息
            String currentName = Optional.ofNullable(StpUtil.getSession().getModel("user", User.class).getName()).orElse("未知用户");
            String currentEmail = Optional.ofNullable(StpUtil.getSession().getModel("user", User.class).getEmail()).orElse("未知邮箱");
            String currentPhone = Optional.ofNullable(StpUtil.getSession().getModel("user", User.class).getPhone()).orElse("未知电话");
            String msg = "";
            Post post = postMapper.selectByPrimaryKey(employ.getPostId());
            if (StringUtils.isEmpty(employ.getFirstPeople())) {
                msg = "您的简历已经成功投递至" + post.getName() + ",请等待管理员审核后，将再次为您发送邮件！";
            } else {
                msg = "您的投递状态发生变更，请前往招聘官网查看最新进度！";
            }
            String template = "<h1 >请注意," + msg + "</h2><br/>" +
                    "<h3 style='font-weight: bold'>发件人：" + currentName + "</h3><br/>" +
                    "<h3 style='font-weight: bold'>邮箱：" + currentEmail + "</h3><br/>" +
                    "<h3 style='font-weight: bold'>电话：" + currentPhone + "</h3><br/>" +
                    "<p>&nbsp;</p>\n";
            Objects.requireNonNull(javaMailSender, "邮件属性未配置");
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
            helper.setSubject("【高校教师聘用信息管理系统】");
            // 获取需要通知的对象，即创建投递信息的用户
            User toUser = userMapper.selectByPrimaryKey(Long.valueOf(employ.getCreateBy()));
            Objects.requireNonNull(toUser, "收件人邮箱未设置");
            helper.setTo(toUser.getEmail());
            helper.setFrom(Objects.requireNonNull(javaMailSender.getUsername()));
            helper.setText(template, true);
            javaMailSender.send(mimeMessage);
            return "邮件发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "邮件发送失败";
        }
    }
}
